package svc

import (
	"album/internal/config"
	"album/internal/database"
	"github.com/IBM/sarama"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/zrpc"
	"go.uber.org/zap"
	"grpc-common/search/scclient"
	"grpc-common/ucenter/ucclient"
	"listenboos-common/db"
)

type ServiceContext struct {
	Config      config.Config
	Cache       cache.Cache
	DB          *db.ListenDB
	KafkaClient sarama.Client
	UCLoginRpc  ucclient.Login
	SearchRpc   scclient.Search
	MongoClient *database.MongoClient
}

func NewServiceContext(c config.Config) *ServiceContext {
	client := InitKafkaClient()

	redisCache := cache.New(c.CacheRedis, nil,
		cache.NewStat("album"), nil, func(o *cache.Options) {})
	return &ServiceContext{
		Config:      c,
		Cache:       redisCache,
		DB:          database.ConnMysql(c.Mysql.DataSource),
		UCLoginRpc:  ucclient.NewLogin(zrpc.MustNewClient(c.UCenterRpc)),
		SearchRpc:   scclient.NewSearch(zrpc.MustNewClient(c.SearchRpc)),
		MongoClient: database.ConnectMongo(c.Mongo),
		KafkaClient: client,
	}
}
func InitKafkaClient() sarama.Client {
	saramaCfg := sarama.NewConfig()
	saramaCfg.Producer.Return.Successes = true
	client, err := sarama.NewClient([]string{"127.0.0.1:9094"}, saramaCfg)
	if err != nil {
		zap.L().Error("kafka consumer InitKafkaClient:", zap.Error(err))
		return nil
	}
	return client
}
